<script setup>
import { onMounted, ref } from 'vue';
import 'cesium/Build/Cesium/Widgets/widgets.css';
// 引入Element Plus和按钮组件
import { ElButton, ElCard, ElDivider } from 'element-plus';
import 'element-plus/dist/index.css';
import * as Cesium from 'cesium';
// 导入Cesium管理器和图层控制模块
import { CesiumManager } from '@/utils/CesiumManager';
import { LayerControlModule } from '@/modules/LayerControl';
import { MapBusinessOperations } from '@/modules/MapBusinessOperations';
import { MapTools } from '@/modules/MapTools';
import { GeometryDrawing } from '@/modules/GeometryDrawing';
// 导入新添加的模块
import { MeasurementTools } from '@/modules/MeasurementTools';
import { AnalysisTools } from '@/modules/AnalysisTools';
import { TrajectoryTools } from '@/modules/TrajectoryTools';
import { AppearanceManager } from '@/modules/AppearanceManager';

// 控制卡片显示状态
const showControlCard = ref(true);
// 控制弹出框显示状态
const showPopup = ref(false);
const popupPosition = ref({ x: 0, y: 0 });
const popupContent = ref('');

let cesiumManager = null;
let layerControl = null;
let mapBusinessOps = null;
let mapTools = null;
let geometryDrawing = null;
// 新增模块实例
let measurementTools = null;
let analysisTools = null;
let trajectoryTools = null;

let appearanceManager = null;

// 初始化Cesium
onMounted(() => {
  // 创建Cesium管理器实例
  cesiumManager = new CesiumManager('cesiumContainer');
  cesiumManager.init();

  // 创建图层控制模块并注册
  layerControl = new LayerControlModule();
  cesiumManager.registerModule('layerControl', layerControl);

  // 创建地图业务操作模块
  mapBusinessOps = new MapBusinessOperations(cesiumManager);

  // 创建地图工具模块
  mapTools = new MapTools(cesiumManager);

  // 创建几何图形绘制模块
  geometryDrawing = new GeometryDrawing(cesiumManager);

  // 创建测量工具模块
  measurementTools = new MeasurementTools(cesiumManager);

  // 创建分析工具模块
  analysisTools = new AnalysisTools(cesiumManager);

  // 创建轨迹工具模块
  trajectoryTools = new TrajectoryTools(cesiumManager);

  appearanceManager = new AppearanceManager(cesiumManager);

  // 添加点击事件监听器
  const viewer = cesiumManager.viewer;
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler.setInputAction(function (click) {
    // 将屏幕坐标转换为笛卡尔坐标
    const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
    if (cartesian) {
      // 获取屏幕坐标
      const screenPosition = click.position;
      // 设置弹出框位置
      popupPosition.value = {
        x: screenPosition.x,
        y: screenPosition.y
      };

      // 获取位置信息
      const position = viewer.camera.positionCartographic;
      const height_new = position.height.toFixed(2);
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
      const ellipsoidHeight = cartographic.height.toFixed(2);

      // 检查是否有有效的地形提供器
      if (viewer.terrainProvider &&
        viewer.terrainProvider.ready &&
        !(viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider)) {
        // 使用sampleTerrain获取地形高度
        Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, [Cesium.Cartographic.fromDegrees(
          parseFloat(longitude),
          parseFloat(latitude)
        )]).then(function (updatedPositions) {
          const height = updatedPositions[0].height.toFixed(2);

          popupContent.value = `
            <h3>位置信息</h3>
            <p><strong>经度:</strong> ${longitude}°</p>
            <p><strong>纬度:</strong> ${latitude}°</p>
            <p><strong>高度:</strong> ${height_new} 米</p>
            <p><strong>时间:</strong> ${new Date().toLocaleString()}</p>
            <button onclick="closePopup()" style="margin-top: 10px; padding: 5px 10px; background: #409eff; color: white; border: none; border-radius: 4px; cursor: pointer;">
              关闭
            </button>
          `;

          // 显示弹出框
          showPopup.value = true;
        });
      } else {
        // 如果没有有效的地形提供器，使用椭球体高度
        popupContent.value = `
          <h3>位置信息</h3>
          <p><strong>经度:</strong> ${longitude}°</p>
          <p><strong>纬度:</strong> ${latitude}°</p>
          <p><strong>高度:</strong> ${height_new} 米</p>
          <p><strong>时间:</strong> ${new Date().toLocaleString()}</p>
          <button onclick="closePopup()" style="margin-top: 10px; padding: 5px 10px; background: #409eff; color: white; border: none; border-radius: 4px; cursor: pointer;">
            关闭
          </button>
        `;

        // 显示弹出框
        showPopup.value = true;
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});

// 关闭弹出框的函数
window.closePopup = function () {
  showPopup.value = false;
};

// 新增图层控制相关函数
const addTerrainLayer = () => {
  // 先设置地形提供器
  const viewer = cesiumManager.viewer;
  viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
    url: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles'
  });

  // 然后添加图层控制
  layerControl.addTerrainLayer('terrain', 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles');
};

const addWmsLayer = () => {
  layerControl.addWmsLayer(
    'wms-layer',
    'https://ahocevar.com/geoserver/wms',
    'topp:states',
    {
      transparent: true,
      format: 'image/png'
    }
  );
};

const addWmtsLayer = () => {
  layerControl.addWmtsLayer(
    'wmts-layer',
    'https://services.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer/WMTS/',
    'World_Topo_Map',
    'default',
    'image/jpeg',
    'GoogleMapsCompatible',
    19
  );
};

const addImageryLayer = () => {
  layerControl.addImageryLayer(
    'imagery-layer',
    'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
  );
};

const addVectorLayer = () => {
  layerControl.addVectorLayer(
    'vector-layer',
    'https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json'
  );
};

const addImageLayer = () => {
  layerControl.addImageLayer(
    'image-layer',
    '/images/sample.png', // 需要提供实际的图片文件
    [110, 27, 115, 30] // 示例范围 [west, south, east, north]
  );
};

const addArcGISMapServerLayer = () => {
  layerControl.addArcGISMapServerLayer(
    'arcgis-layer',
    'https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer'
  );
};

const toggleLayer = () => {
  layerControl.toggleLayer('default');
};

const removeLayer = () => {
  layerControl.removeLayer('default');
};

const setLayerOpacity = () => {
  const opacity = Math.random(); // 随机透明度
  layerControl.setLayerOpacity('default', opacity);
};

// 地图业务操作相关函数
const addPoint = () => {
  mapBusinessOps.addPoint();
};

const addLine = () => {
  mapBusinessOps.addLine();
};

const addPolygon = () => {
  mapBusinessOps.addPolygon();
};

const measureDistance = () => {
  mapBusinessOps.measureDistance();
};

const measureArea = () => {
  mapBusinessOps.measureArea();
};

const clearAll = () => {
  mapBusinessOps.clearAll();
};

// 批量添加点相关函数
const addHundredPoints = () => {
  mapBusinessOps.addRandomPoints(100);
};

const addThousandPoints = () => {
  mapBusinessOps.addRandomPoints(1000);
};

const addTenThousandPoints = () => {
  mapBusinessOps.addRandomPoints(10000);
};

// 常用地图工具相关函数
const zoomIn = () => {
  mapTools.zoomIn();
};
// 漫游功能
const startCityRoaming = () => {
  console.log('开始城市漫游');
  mapTools.startCityRoaming();
};
const zoomOut = () => {
  mapTools.zoomOut();
};

const fullExtent = () => {
  mapTools.fullExtent();
};

const panMode = () => {
  mapTools.panMode();
};

const selectMode = () => {
  mapTools.selectMode();
};

// 新增的点类型相关函数
const addBillboardPoint = () => {
  mapBusinessOps.addBillboardPoint();
};

const addLabeledBillboardPoint = () => {
  mapBusinessOps.addLabeledBillboardPoint();
};

const addRipplePoint = () => {
  mapBusinessOps.addRipplePoint();
};

const addStatusPoint = () => {
  mapBusinessOps.addStatusPoint();
};

const addTextPoint = () => {
  mapBusinessOps.addTextPoint();
};

const addHtmlPoint = () => {
  mapBusinessOps.addHtmlPoint();
};

const addGifPoint = () => {
  mapBusinessOps.addGifPoint();
};

const addGifAggregatedPoint = () => {
  mapBusinessOps.addGifAggregatedPoint();
};

const addAnimatedGifPoint = () => {
  mapBusinessOps.addAnimatedGifPoint();
};

const addDiffuseCircle = () => {
  mapBusinessOps.addDiffuseCircle();
};

const addBillboardDiffuseCircle = () => {
  mapBusinessOps.addBillboardDiffuseCircle();
};

const addAggregatedPoint = () => {
  mapBusinessOps.addAggregatedPoint();
};

const addAggregatedBillboard1 = () => {
  mapBusinessOps.addAggregatedBillboard1();
};

const addAggregatedBillboard2 = () => {
  mapBusinessOps.addAggregatedBillboard2();
};

const addAggregatedBillboard3 = () => {
  mapBusinessOps.addAggregatedBillboard3();
};

const addAdministrativeAggregation = () => {
  mapBusinessOps.addAdministrativeAggregation();
};

const addClickAggregation = () => {
  mapBusinessOps.addClickAggregation();
};

const addBillboardPrimitive = () => {
  mapBusinessOps.addBillboardPrimitive();
};

const clearLayers = () => {
  mapBusinessOps.clearLayers();
};

// 几何图形绘制函数
const addMaterialLine = () => {
  geometryDrawing.addMaterialLine();
};

const addPolygonWithHole = () => {
  geometryDrawing.addPolygonWithHole();
};

const addWaterSurface = () => {
  geometryDrawing.addWaterSurface();
};

const addOverlayPolygon = () => {
  geometryDrawing.addOverlayPolygon();
};

const addCircle = () => {
  geometryDrawing.addCircle();
};

const addRectangle = () => {
  geometryDrawing.addRectangle();
};

const addAttackArrow = () => {
  geometryDrawing.addAttackArrow();
};

const addDoubleArrow = () => {
  geometryDrawing.addDoubleArrow();
};

const addStraightArrow = () => {
  geometryDrawing.addStraightArrow();
};

const addSwallowtailArrow = () => {
  geometryDrawing.addSwallowtailArrow();
};

const addAssemblyArea = () => {
  geometryDrawing.addAssemblyArea();
};

const addTextPlot = () => {
  geometryDrawing.addTextPlot();
};

// 测量工具函数
const measureHeight = () => {
  measurementTools.measureHeight();
};

const circleSelection = () => {
  measurementTools.circleSelection();
};

const rectangleSelection = () => {
  measurementTools.rectangleSelection();
};

const polygonSelection = () => {
  measurementTools.polygonSelection();
};

// 分析工具函数
const pointAnalysis = () => {
  analysisTools.pointAnalysis();
};

const billboardAnalysis = () => {
  analysisTools.billboardAnalysis();
};

const lineAnalysis = () => {
  analysisTools.lineAnalysis();
};

const polygonAnalysis = () => {
  analysisTools.polygonAnalysis();
};

// 轨迹工具函数
const addHistoricalTrajectory = () => {
  trajectoryTools.addHistoricalTrajectory();
};

const addGridPersonConnection = () => {
  trajectoryTools.addGridPersonConnection();
};

const addModelTrajectory = () => {
  trajectoryTools.addModelTrajectory();
};

const playTrajectory = () => {
  trajectoryTools.play();
};

const pauseTrajectory = () => {
  trajectoryTools.pause();
};

const speedUpTrajectory = () => {
  trajectoryTools.speedUp();
};

const speedDownTrajectory = () => {
  trajectoryTools.speedDown();
};

const clearTrajectory = () => {
  trajectoryTools.clear();
};

// 新增功能：撒点加聚合结合
const addScatterAndClusterPoints = () => {
  mapBusinessOps.addScatterAndClusterPoints();
};

const createFireworkEffect = () => { 
  appearanceManager.createRainEffect('Rain')
};
</script>

<template>
  <div id="cesiumContainer" style="width: 100%; height: 100vh;"></div>

  <!-- 在左上角固定一个卡片位置 加入默认的 按钮 -->
  <div class="control-card" v-if="showControlCard">
    <el-card>
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <el-button type="primary">默认按钮</el-button>
        <el-button @click="showControlCard = false">关闭</el-button>
      </div>

      <el-divider />

      <!-- 图层控制 -->
      <div style="margin-top: 10px;">
        <h4>图层控制</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="addTerrainLayer">添加地形</el-button>
          <el-button size="small" @click="addWmsLayer">添加WMS</el-button>
          <el-button size="small" @click="addWmtsLayer">添加WMTS</el-button>
          <el-button size="small" @click="addImageryLayer">添加影像</el-button>
          <el-button size="small" @click="addVectorLayer">添加矢量</el-button>
          <el-button size="small" @click="addImageLayer">添加图片</el-button>
          <el-button size="small" @click="addArcGISMapServerLayer">添加ArcGIS</el-button>
          <el-button size="small" @click="toggleLayer">切换图层</el-button>
          <el-button size="small" @click="removeLayer">移除图层</el-button>
          <el-button size="small" @click="setLayerOpacity">设置透明度</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 地图业务操作 -->
      <div style="margin-top: 10px;">
        <h4>地图业务操作</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="addPoint">点</el-button>
          <el-button size="small" @click="addLine">线</el-button>
          <el-button size="small" @click="addPolygon">面</el-button>
          <el-button size="small" @click="measureDistance">距离</el-button>
          <el-button size="small" @click="measureArea">面积</el-button>
          <el-button size="small" type="danger" @click="clearAll">清除</el-button>
          <!-- 新增批量添加点按钮 -->
          <el-button size="small" @click="addHundredPoints">100点</el-button>
          <el-button size="small" @click="addThousandPoints">1000点</el-button>
          <el-button size="small" @click="addTenThousandPoints">10000点</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 点类型操作 -->
      <div style="margin-top: 10px;">
        <h4>点类型</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="addBillboardPoint">图标点</el-button>
          <el-button size="small" @click="addLabeledBillboardPoint">图标点(L)</el-button>
          <el-button size="small" @click="addRipplePoint">图标点(水波)</el-button>
          <el-button size="small" @click="addStatusPoint">图标点(状态)</el-button>
          <el-button size="small" @click="addTextPoint">文本点</el-button>
          <el-button size="small" @click="addHtmlPoint">HTML点</el-button>
          <el-button size="small" @click="addGifPoint">GIF点</el-button>
          <el-button size="small" @click="addAnimatedGifPoint">GIF点(动画)</el-button>
          <el-button size="small" @click="addGifAggregatedPoint">GIF点(聚合)</el-button>
          <!-- 新增的撒点加聚合结合按钮 -->
          <el-button size="small" @click="addScatterAndClusterPoints">撒点聚合</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 圆形和聚合操作 -->
      <div style="margin-top: 10px;">
        <h4>圆形与聚合</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="addDiffuseCircle">扩散圆</el-button>
          <el-button size="small" @click="addBillboardDiffuseCircle">图标点(扩散)</el-button>
          <el-button size="small" @click="addAggregatedPoint">聚合点</el-button>
          <el-button size="small" @click="addAggregatedBillboard1">聚合图标1</el-button>
          <el-button size="small" @click="addAggregatedBillboard2">聚合图标2</el-button>
          <el-button size="small" @click="addAggregatedBillboard3">聚合图标3</el-button>
          <el-button size="small" @click="addAdministrativeAggregation">行政聚合</el-button>
          <el-button size="small" @click="addClickAggregation">单击事件(聚合)</el-button>
          <el-button size="small" @click="addBillboardPrimitive">图标点(图元)</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 几何图形绘制 -->
      <div style="margin-top: 10px;">
        <h4>几何图形绘制</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="addMaterialLine">材质线</el-button>
          <el-button size="small" @click="addPolygonWithHole">空洞面</el-button>
          <el-button size="small" @click="addWaterSurface">水面动画</el-button>
          <el-button size="small" @click="addOverlayPolygon">覆盖面</el-button>
          <el-button size="small" @click="addCircle">圆</el-button>
          <el-button size="small" @click="addRectangle">矩形</el-button>
          <el-button size="small" @click="addAttackArrow">进攻箭头</el-button>
          <el-button size="small" @click="addDoubleArrow">双箭头</el-button>
          <el-button size="small" @click="addStraightArrow">直箭头</el-button>
          <el-button size="small" @click="addSwallowtailArrow">燕尾箭头</el-button>
          <el-button size="small" @click="addAssemblyArea">聚集地</el-button>
          <el-button size="small" @click="addTextPlot">文本标绘</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 测量工具 -->
      <div style="margin-top: 10px;">
        <h4>测量工具</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="measureHeight">高度测量</el-button>
          <el-button size="small" @click="circleSelection">圆形框选</el-button>
          <el-button size="small" @click="rectangleSelection">矩形框选</el-button>
          <el-button size="small" @click="polygonSelection">多边形框选</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 分析工具 -->
      <div style="margin-top: 10px;">
        <h4>分析工具</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="pointAnalysis">点分析</el-button>
          <el-button size="small" @click="billboardAnalysis">图标分析</el-button>
          <el-button size="small" @click="lineAnalysis">线分析</el-button>
          <el-button size="small" @click="polygonAnalysis">面分析</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 轨迹工具 -->
      <div style="margin-top: 10px;">
        <h4>轨迹工具</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="addHistoricalTrajectory">历史轨迹</el-button>
          <el-button size="small" @click="addGridPersonConnection">网格连接</el-button>
          <el-button size="small" @click="addModelTrajectory">模型轨迹</el-button>
          <el-button size="small" @click="playTrajectory">播放</el-button>
          <el-button size="small" @click="pauseTrajectory">暂停</el-button>
          <el-button size="small" @click="speedUpTrajectory">加速</el-button>
          <el-button size="small" @click="speedDownTrajectory">减速</el-button>
          <el-button size="small" type="danger" @click="clearTrajectory">清除轨迹</el-button>
        </div>
      </div>

      <el-divider />

      <!-- 常用地图工具 -->
      <div style="margin-top: 10px;">
        <h4>地图工具</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="zoomIn">放大</el-button>
          <el-button size="small" @click="zoomOut">缩小</el-button>
          <el-button size="small" @click="fullExtent">全图</el-button>
          <el-button size="small" @click="panMode">平移</el-button>
          <el-button size="small" @click="selectMode">选择</el-button>
          <el-button size="small" type="danger" @click="clearLayers">清除图层</el-button>
        </div>
      </div>
      <div style="margin-top: 10px;">
        <h4>摄像头工具</h4>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
          <el-button size="small" @click="startCityRoaming">城市漫游功能</el-button>
          <el-button size="small" @click="createFireworkEffect">烟花效果</el-button>
        </div>
      </div>

    </el-card>
  </div>

  <!-- 弹出框 -->
  <div v-if="showPopup" class="popup" :style="{ left: popupPosition.x + 'px', top: popupPosition.y + 'px' }">
    <div class="popup-content" v-html="popupContent"></div>
  </div>
</template>

<style scoped>
#cesiumContainer {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

/* 添加默认背景以防图像加载失败 */
#cesiumContainer::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #000;
  z-index: -1;
}

/* 左上角固定卡片样式 */
.control-card {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  max-height: 90vh;
  overflow-y: auto;
}

/* 弹出框样式 */
.popup {
  position: absolute;
  z-index: 2000;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transform: translate(-50%, -100%);
  margin-top: -20px;
  min-width: 250px;
  max-width: 400px;
}

.popup-content {
  padding: 15px;
}

.popup-content h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.popup-content p {
  margin: 5px 0;
  color: #666;
}
</style>